from django.db import models
from user.models import User
from product.models import Product

# 订单状态枚举
ORDER_STATUS_CHOICES = (
    ('pending', '待支付'),
    ('paid', '已支付'),
    ('shipped', '已发货'),
    ('completed', '已完成'),
    ('cancelled', '已取消'),
)

class Order(models.Model):
    # 订单基本信息
    order_number = models.CharField(max_length=50, unique=True, verbose_name='订单号')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders', verbose_name='用户')
    order_time = models.DateTimeField(auto_now_add=True, verbose_name='下单时间')
    status = models.CharField(max_length=20, choices=ORDER_STATUS_CHOICES, default='pending', verbose_name='订单状态')
    total_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='订单总价')
    
    # 订单相关信息
    shipping_address = models.TextField(blank=True, null=True, verbose_name='收货地址')
    contact_phone = models.CharField(max_length=20, blank=True, null=True, verbose_name='联系电话')
    
    class Meta:
        verbose_name = '订单'
        verbose_name_plural = '订单'
        ordering = ['-order_time']
    
    def __str__(self):
        return f'订单 {self.order_number} - {self.user.username}'

class OrderItem(models.Model):
    # 订单项信息，关联到订单和商品
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items', verbose_name='订单')
    product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='order_items', verbose_name='商品')
    product_name = models.CharField(max_length=200, verbose_name='商品名称')  # 冗余存储，防止商品信息变更
    product_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='商品单价')  # 冗余存储
    product_image = models.CharField(max_length=255, blank=True, null=True, verbose_name='商品图片')  # 冗余存储
    quantity = models.IntegerField(default=1, verbose_name='商品数量')
    subtotal = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='商品小计')
    
    class Meta:
        verbose_name = '订单项'
        verbose_name_plural = '订单项'
    
    def __str__(self):
        return f'{self.product_name} - {self.quantity}件'
    
    # 保存前自动计算小计
    def save(self, *args, **kwargs):
        self.subtotal = self.product_price * self.quantity
        super().save(*args, **kwargs)
